<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <!-- 消息警告 -->
      <el-alert title="消息提示的文案" type="info" center show-icon :closable="false"> </el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 表单 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
        <!-- tab栏区域 -->
        <el-tabs v-model="activeIndex" :tab-position="'left'" :before-leave="beforeTagsLeave" @tab-click="tabClick">
          <!-- 1 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader v-model="addForm.goods_cat" :options="categoriesList" :props="selectProp" @change="selectChange"> </el-cascader>
            </el-form-item>
          </el-tab-pane>

          <!-- 2-->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manyDataList" :key="item.attr_id" :label="item.attr_name">
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="val" v-for="(val, i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <!-- 3 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in onlyDataList" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>

          <!-- 4 -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload :action="uploadURL" :headers="headersObj" :on-preview="handlePreview" :on-remove="handleRemove" :on-success="picSuccess" list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>

          <!-- 5 -->
          <el-tab-pane label="商品内容" name="4">
            <template>
              <!-- bidirectional data binding（双向数据绑定） -->
              <!-- 父文本编辑器 -->
              <quill-editor v-model="addForm.goods_introduce" ref="myQuillEditor"> </quill-editor>
              <el-button type="primary" @click="add">添加商品</el-button>
            </template>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 预览图片的对话框 -->
    <el-dialog title="查看图片" :visible.sync="vuewDialogVisible" width="50%">
      <img :src="viewPath" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import _ from "lodash"
export default {
  data() {
    return {
      activeIndex: "0",
      // 添加表单的数据对象
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // select 返回的选中分类id值 添加表单的  以为','分割的分类列表
        goods_cat: [],
        pics: [],
        goods_introduce: "", //介绍
        attrs: [] //动态参数和静态属性
      },
      // 添加表单的验证规则
      addFormRules: {
        goods_name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        goods_price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
        goods_weight: [{ required: true, message: "请输入商品重量", trigger: "blur" }],
        goods_number: [{ required: true, message: "请输入商品数量", trigger: "blur" }],
        goods_cat: [{ required: true, message: "请输入商品分类", trigger: "blur" }]
      },
      // 分类列表
      categoriesList: [],
      // selsect 的props配置项
      selectProp: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      // 动态参数列表
      manyDataList: [],
      // 静态属性列表
      onlyDataList: [],
      // 上传图片的地址
      uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
      // 图片上传的请求头设置
      headersObj: {
        Authorization: window.sessionStorage.getItem("token")
      },
      // 进行查看的图片地址
      viewPath: "",
      // 预览图片的对话框控制
      vuewDialogVisible: false
    }
  },
  computed: {
    getCateId() {
      if (this.addForm.goods_cat.length == 3) {
        return this.addForm.goods_cat[2]
      } else {
        return null
      }
    }
  },
  created() {
    this.getCategories()
  },
  methods: {
    // 商品分类数据列表
    async getCategories() {
      var { data: res } = await this.$http.get("categories")
      if (res.meta.status !== 200) return this.$message.error("获取分类数据失败")
      this.$message.success("获取分类数据成功")
      this.categoriesList = res.data
      console.log(res)
      console.log(this.categoriesList)
    },
    // select文本框发生改变的时候
    selectChange() {
      console.log(this.addForm.goods_cat)
      // 我们只能选中有三项的级联分类，
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // 当tags标签离开前会触发 控制没填完不允许进入下一个标签
    beforeTagsLeave(activeName, oldActiveName) {
      if (this.addForm.goods_cat.length === 0 || this.addForm.goods_cat.length !== 3) {
        this.$message.error("请选择商品分类")
        return false
      }
    },
    // 选中tabs 触发
    async tabClick() {
      if (this.activeIndex == 1) {
        const { data: res } = await this.$http.get(`categories/${this.getCateId}/attributes`, {
          params: { sel: "many" }
        })
        if (res.meta.status !== 200) return this.$message.error("获取参数列表失败")
        console.log(res.data)

        this.manyDataList = res.data
        // this.manyDataList.attr_vals = res.data.attr_vals.join(" ")
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ")
        })
        console.log(res.data)
      } else if (this.activeIndex == 2) {
        const { data: res } = await this.$http.get(`categories/${this.getCateId}/attributes`, {
          params: { sel: "only" }
        })
        if (res.meta.status !== 200) return this.$message.error("获取静态属性列表失败")
        this.onlyDataList = res.data
        console.log(this.onlyDataList)
      }
    },
    // 处理图片预览
    handlePreview(file) {
      console.log(file)
      this.viewPath = file.response.data.url
      this.vuewDialogVisible = true
    },
    // 处理移除图片的操作
    handleRemove(file) {
      console.log(file) //移除的那一项
      const i = this.addForm.pics.findIndex(item => {
        return item.pic == file.response.data.tmp_path
      })
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm)
    },
    // 上传图片成功返回的钩子函数
    picSuccess(response) {
      const obj = { pic: response.data.tmp_path }
      this.addForm.pics.push(obj)
      console.log(response)
    },
    // 添加商品
    add() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error("请填写完整信息")
        }
        // 预验证通过后执行相应的逻辑
        // 我们要深拷贝传过去的参数对象 因为 表单中goods_cat要求绑定为数组，但是
        // 我们接口传过去要去字符串 用到依赖 lodash 的cloneDeep 项
        const value = _.cloneDeep(this.addForm)
        value.goods_cat = value.goods_cat.join(",")
        console.log(value)
        // 动态参数的处理
        this.manyDataList.forEach(item => {
          const pp = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" ")
          }
          this.addForm.attrs.push(pp)
        })
        // 静态属性的处理
        this.onlyDataList.forEach(item => {
          const pp = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(pp)
        })
        console.log(this.addForm)
        value.attrs = this.addForm.attrs
        console.log(value)
        // 发请求
        // 商品名称不能重复
        const { data: res } = await this.$http.post("goods", value)
        if (res.meta.status !== 201) return this.$message.error("添加商品失败")
        this.$message.success("添加成功")
        this.$router.push("/goods")
      })
    }
  }
}
</script>
<style scoped>
.el-steps {
  margin: 15px 0;
}
.el-steps .el-step__title {
  font-size: 13px;
  text-align: center;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.el-dialog img {
  width: 100%;
}
.el-button {
  margin-top: 15px;
}
</style>
